import 'package:flutter/material.dart';
import 'package:macnov/models/company.dart';
import 'package:macnov/utils/Api.dart';
import 'package:macnov/utils/constant.dart';
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';

// Include generated file
part 'signin.g.dart';

// This is the class used by rest of your codebase
class Signin = _Signin with _$Signin;

const MACNOV_LOCK_SCREEN_OPT = 'loginOpt';
const MACNOV_LOCK_SCREEN_PWD = 'loginPwd';

// The store-class
abstract class _Signin extends ChangeNotifier with Store {
  @observable
  dynamic avatarInfo;

  @observable
  String lastestUser = '';
  @observable
  String lastestPassword = '';
  @observable
  UserInfoModel userInfo = new UserInfoModel('', '', '', '');

  @observable
  bool needAuth = true;

  @action
  void setAvatar(data) {
    avatarInfo = data;
  }

  // pin email touchid
  saveLastLoginOption(LoginOpt type, String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt(MACNOV_LOCK_SCREEN_OPT, type.index);
    prefs.setString(MACNOV_LOCK_SCREEN_PWD, value);
  }

  void signOut() async {
    var result = await Api.signOut();
    print('signOut :$result');
  }

  Future<LoginOpt> loadLastLoginOption() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    try {
      LoginOpt loginOpt = LoginOpt.values[prefs.getInt(MACNOV_LOCK_SCREEN_OPT)];
      return loginOpt;
    } catch (e) {
      return null;
    }
  }

  Future<String> loadLastLoginPwd() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    try {
      String loginPwd = prefs.getString(MACNOV_LOCK_SCREEN_PWD);
      return loginPwd;
    } catch (e) {
      return null;
    }
  }

  @action
  Future saveLastAccount(email, pwd) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('email', email);
    prefs.setString('pwd', pwd);
    saveAccount(email, pwd);
    return true;
  }

  @action
  void saveAccount(email, pwd) {
    lastestUser = email;
    lastestPassword = pwd;
  }

  @action
  Future loadLastAccount() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    try {
      String emailString = prefs.getString('email');
      String pwdString = prefs.getString('pwd');

      if (emailString != null && pwdString != null) {
        lastestUser = emailString;
        lastestPassword = pwdString;

        print('emailString# $emailString');
        print('pwdString# $pwdString');
      }
      return true;
    } catch (e) {}
  }

  @action
  Future loadUserSetting() async {
    var data = await Api.loadUserSetting();
    userInfo = UserInfoModel.fromJson(data);
  }

  @action
  Future getAvatar() async {
    var avatarInfoJson = await Api.getAvatar();
    avatarInfo = avatarInfoJson;
  }
}

final Signin signInStore = new Signin();
